//
//  YWDownloadMetaDataManager.m
//  maintain
//
//  Created by 郑想 on 15/12/22.
//  Copyright © 2015年 ewin. All rights reserved.
//
#import "SSZipArchive.h"
#import "MJExtension.h"
#import "WMHttpTool.h"
#import "YWAliyunOSSManager.h"
#import "YWBuilding.h"
#import "YWBuildingJson.h"
#import "YWBuildingManager.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWEquipmentType.h"
#import "YWDownloadMetaDataManager.h"
#import "YWEquipment.h"
#import "YWEquipmentManager.h"
#import "YWEquipmentRulesJson.h"
#import "YWHandler.h"
#import "YWLastMaintenanceTime.h"
#import "YWMacro.h"
#import "YWMissionManager.h"
#import "YWResourceManager.h"
#import "YWEwinMenu.h"
#import "YWEwinManager.h"
#import "YWEquipmentUseMenthod.h"
#import "YWEquipmentUseRange.h"

@interface YWDownloadMetaDataManager ()
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
@end

@implementation YWDownloadMetaDataManager
YWSingletonM(Manager)

//    - (dispatch_queue_t)serialQueue
//{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("DownloadMetaDataSerialQueue", DISPATCH_QUEUE_SERIAL); //创建下载串行队列
//    }
//    return _serialQueue;
//}

- (void)serialDownloadDatasWithComplete:(void (^)(BOOL error))complete
{
    __block BOOL isError = NO;
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_group_enter(group);
        [self downloadEquipmentTypeWithComplete:^(BOOL error) {
            if (error) {
                //设备类型
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadEquipmentRuntimeParameterWithComplete:^(BOOL error) {
            if (error) {
                //设备运行参数
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadEwinMenuWithComplete:^(BOOL error) {
            if (error) {
                //菜单
                isError = error;
            }
            dispatch_group_leave(group);
        }];

        dispatch_group_enter(group);
        [self downloadBuildingWithComplete:^(BOOL error) {
            if (error) {
                //楼盘，设备，规则
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadEquipmentUseMethodWithComplete:^(BOOL error) {
            if (error) {
                //设备使用方法
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadEquipmentUseRangeWithComplete:^(BOOL error) {
            if (error) {
                //设备使用范围
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadBuildingMembersWithComplete:^(BOOL error) {
            if (error) {
                //所有楼盘下的成员
                isError = error;
            }
            dispatch_group_leave(group);
            
            dispatch_group_enter(group);
            [self downloadOrganizationMembersWithComplete:^(BOOL error) {
                if (error) {
                    //当前组织机构的成员
                    isError = error;
                }
                dispatch_group_leave(group);
            }];
        }];
        
        dispatch_group_enter(group);
        [[YWEwinManager shareManager] requesNoQrcodeRightsWithBlock:^(BOOL succeed) {
            if (!succeed) {
                //无二维码工作权限
                isError = !succeed;
            }
            dispatch_group_leave(group);
        }];

        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(isError);
            }
        });
    });
}

- (void)downloadDatasWithType:(YWJsonRefreshType)type{
    switch (type) {
        case YWJsonRefreshTypeEquipmentRule:
            [self downloadBuildingWithComplete:nil];
            break;
        case YWJsonRefreshTypeBuilding:
            [self downloadBuildingWithComplete:nil];
            break;
        case YWJsonRefreshTypeEquipment:
            [self downloadBuildingWithComplete:nil];
            break;
        case YWJsonRefreshTypeEquipmentRuntime:
            //运行参数
            [self downloadEquipmentRuntimeParameterWithComplete:nil];
            break;
        case YWJsonRefreshTypeEquipmentType:
            [self downloadEquipmentTypeWithComplete:nil];
            break;
        default:
            break;
    }
}

- (void)refreshJsonDatasWithComplete:(void (^)(BOOL))complete{
    __block BOOL isError = NO;
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_group_enter(group);
        [self downloadEquipmentTypeWithComplete:^(BOOL error) {
            if (error) {
                //设备类型
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadEquipmentRuntimeParameterWithComplete:^(BOOL error) {
            if (error) {
                //设备运行参数
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadEwinMenuWithComplete:^(BOOL error) {
            if (error) {
                //菜单
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self refreshDownloadBuildingWithComplete:^(BOOL error) {
            if (error) {
                //楼盘，设备，规则
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadEquipmentUseMethodWithComplete:^(BOOL error) {
            if (error) {
                //设备使用方法
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadEquipmentUseRangeWithComplete:^(BOOL error) {
            if (error) {
                //设备使用范围
                isError = error;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self downloadBuildingMembersWithComplete:^(BOOL error) {
            if (error) {
                //所有楼盘下的成员
                isError = error;
            }
            dispatch_group_leave(group);
            
            dispatch_group_enter(group);
            [self downloadOrganizationMembersWithComplete:^(BOOL error) {
                if (error) {
                    //当前组织机构的成员
                    isError = error;
                }
                dispatch_group_leave(group);
            }];
        }];
        
        dispatch_group_enter(group);
        [[YWEwinManager shareManager] requesNoQrcodeRightsWithBlock:^(BOOL succeed) {
            if (!succeed) {
                //无二维码工作权限
                isError = !succeed;
            }
            dispatch_group_leave(group);
        }];
        
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(isError);
            }
        });
    });
}

- (void)downloadWithUrl:(NSString*)url params:(NSDictionary*)params complete:(void (^)(BOOL isError, id json))complete
{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(YES,nil);}return;}
    
    [[WMHttpTool shareHttpTool] getWithUrl:url
        params:params
        success:^(NSHTTPURLResponse* response, id json) {
            if (complete) {
                complete(NO, json);
            }
        }
        failure:^(NSHTTPURLResponse* response, NSError* error) {
            YWLog(@"url:%@,%s,error:%@,statusCode:%ld",url,__func__, error.localizedDescription,(long)response.statusCode);
            if (complete) {
                complete(YES, nil);
            }
        }];
}

- (void)downloadEquipmentTypeWithComplete:(void (^)(BOOL error))complete
{
    NSTimeInterval updateTime = [[YWEquipmentManager shareManager]dicEquipmentTypeMaxUpdateTime];
    NSDictionary *params = nil;
    if (updateTime) {
        params = @{@"startTime":@(updateTime)};
    }
    [self downloadWithUrl:[YWCommonTool getEquipmentTypeUrl] params:params complete:^(BOOL error, id json) {
        if (!error) {
            NSArray* dictEquipmentTypes = [YWEquipmentType mj_objectArrayWithKeyValuesArray:json];
            [[YWEquipmentManager shareManager] saveEquipmentTypeWithArray:dictEquipmentTypes];
        }
        if (complete) {
            complete(error);
        }
    }];
}

- (void)downloadEquipmentRuntimeParameterWithComplete:(void (^)(BOOL error))complete
{
    NSTimeInterval createTime = [[YWEquipmentManager shareManager] dicEquipmentRuntimeParameterMaxCreateTime];
    NSDictionary *params = @{@"createTime" :@(createTime)};
    [self downloadWithUrl:[YWCommonTool getEquipmentRuntimeParameterUrl] params:params complete:^(BOOL error, id json) {
         if (!error) {
             NSArray* runtimeParameters = [YWRunTimeParameter mj_objectArrayWithKeyValuesArray:json];
             //保存设备运行参数
             [[YWEquipmentManager shareManager] saveRuntimeParameterWithArray:runtimeParameters];
         }
        if (complete) {
            complete(error);
        }
    }];
}

- (void)downloadEquipmentUseMethodWithComplete:(void (^)(BOOL error))complete
{
    NSTimeInterval updateTime = [[YWEquipmentManager shareManager] useMenthodMaxUpdateTime];
    NSDictionary *params = @{@"updateTime" :@(updateTime)};
    [self downloadWithUrl:[YWCommonTool getEquipmentUseMethodUrl] params:params complete:^(BOOL error, id json) {
        if (!error) {
            NSArray* useMethodArray = [YWEquipmentUseMenthod mj_objectArrayWithKeyValuesArray:json];
            //保存设备使用方法
            [[YWEquipmentManager shareManager] updateEquipmentUseMenthodWithArray:useMethodArray];
        }
        if (complete) {
            complete(error);
        }
    }];
}

- (void)downloadEquipmentUseRangeWithComplete:(void (^)(BOOL error))complete
{
    NSTimeInterval updateTime = [[YWEquipmentManager shareManager] useMenthodMaxUpdateTime];
    NSDictionary *params = @{@"updateTime" :@(updateTime)};
    [self downloadWithUrl:[YWCommonTool getEquipmentUseRangeUrl] params:params complete:^(BOOL error, id json) {
        if (!error) {
            NSArray* useRangeArray = [YWEquipmentUseRange mj_objectArrayWithKeyValuesArray:json];
            //保存设备使用范围
            [[YWEquipmentManager shareManager] updateEquipmentUseRangeWithArray:useRangeArray];
        }
        if (complete) {
            complete(error);
        }
    }];
}

- (void)downloadBuildingWithComplete:(void (^)(BOOL error))complete
{
//    YWWeakSelf(weakself);
    [self downloadWithUrl:[YWCommonTool getBuildingJsonUrl] params:nil complete:^(BOOL error, id json) {
        if (!error) {
            if ([json isKindOfClass:[NSArray class]]) {
                NSArray* buildingJsonFiles = [YWBuildingJsonFile mj_objectArrayWithKeyValuesArray:json];
                if (buildingJsonFiles.count == 0) {
                    if (complete) {
                        complete(YES);
                    }
                }
                //每个buildingJsonFiles包含楼盘设备规则3个文件
                __block NSInteger downloadCount = buildingJsonFiles.count * 3;
                __block NSMutableArray* allBuildings = [NSMutableArray array];
                __block NSMutableArray* allEquipments = [NSMutableArray array];
                __block NSMutableArray* allRules = [NSMutableArray array];
                __block YWLoginUser *currentUser = [YWLoginTool loginUser];
                //楼盘
                [buildingJsonFiles enumerateObjectsUsingBlock:^(YWBuildingJsonFile*  _Nonnull buildingJsonFile, NSUInteger idx, BOOL * _Nonnull stop) {
                    YWBuilding* building = [[YWBuildingManager shareManager] buildingWithId:buildingJsonFile.buildingId];
                    if (building==nil||building.buildingJsonFileUpdateTime != buildingJsonFile.buildingJsonFileUpdateTime) {
                        NSString *path = [NSString stringWithFormat:@"%@_buildingZipFile.zip",buildingJsonFile.buildingId];
                        NSString *fullPath = [[YWResourceManager shareManager] fileCachePathFromResourcePath:path];
                        path = [NSString stringWithFormat:@"/buildingUnZipFile_%@",buildingJsonFile.buildingId];
                        NSString *outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];
                        [[YWAliyunOSSManager shareManager] downloadFile:buildingJsonFile.buildingJsonUrl toFilePath:fullPath progressBlock:nil completeBlock:^(BOOL success) {
                            if (success) {
                                //data为zip格式数据 解压
                                NSData *data = [self UnzipFromZipFile:fullPath toPath:outputPath];
                                YWBuildingJson* buildingJson = nil;
                                if (data) {
                                    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                    buildingJson = [YWBuildingJson mj_objectWithKeyValues:jsonDict];
                                }
                                if (buildingJson) {
                                    buildingJson.equipmentJsonFileUpdateTime = buildingJsonFile.equipmentJsonFileUpdateTime;
                                    buildingJson.buildingJsonFileUpdateTime = buildingJsonFile.buildingJsonFileUpdateTime;
                                    buildingJson. ruleJsonFileUpdateTime= buildingJsonFile.ruleJsonFileUpdateTime;
                                    [allBuildings addObject:buildingJson];
                                }
                            }
                            @synchronized(NSStringFromSelector(_cmd)) {
                                downloadCount--;
                                if (downloadCount == 0) {
                                    [[YWBuildingManager shareManager] savebuildingJsonWithArray:allBuildings];
                                    [[YWEquipmentManager shareManager] saveEquipmentsWithArray:allEquipments];
                                    [[YWEquipmentManager shareManager] saveEquipmentRulesWithArray:allRules];
                                    if (complete) {
                                        complete(error);
                                    }
                                }
                            }
                        }];
                    }else {
                        downloadCount--;
                        if (downloadCount == 0) {
                            if (complete) {
                                complete(error);
                            }
                        }
                    }
                    //设备
                    NSString *key = [NSString stringWithFormat:@"%ld_%@_equipment12hour",(long)currentUser.uniqueId,buildingJsonFile.buildingId];
                    long long updateTime = [[[NSUserDefaults standardUserDefaults] objectForKey:key] longLongValue];
                    long long interval = ([YWCommonTool negativeTimestampId] - updateTime)/3600000000;
                    if (updateTime==0 || interval>=12) {
                        if (building==nil||building.equipmentJsonFileUpdateTime != buildingJsonFile.equipmentJsonFileUpdateTime) {
                            NSString *path = [NSString stringWithFormat:@"%@_equipmentZipFile.zip",buildingJsonFile.buildingId];
                            NSString *fullPath = [[YWResourceManager shareManager] fileCachePathFromResourcePath:path];
                            
                            path = [NSString stringWithFormat:@"/equipmentUnZipFile_%@",buildingJsonFile.buildingId];
                            NSString *outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];
                            [[YWAliyunOSSManager shareManager] downloadFile:buildingJsonFile.equipmentJsonUrl  toFilePath:fullPath progressBlock:nil completeBlock:^(BOOL success) {
                                if (success) {
                                    //data为zip 解压
                                    NSData *data = [self UnzipFromZipFile:fullPath toPath:outputPath];
                                    NSArray* equipments = nil;
                                    if (data) {
                                        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                        equipments = [YWEquipment mj_objectArrayWithKeyValuesArray:jsonDict];
                                    }
                                    
                                    if (equipments.count>0) {
                                        [allEquipments addObjectsFromArray:equipments];
                                        long long updateTime = buildingJsonFile.equipmentJsonFileUpdateTime*1000;
                                        [[NSUserDefaults standardUserDefaults] setObject:@(updateTime) forKey:key];
                                        [[NSUserDefaults standardUserDefaults] synchronize];
                                    }
                                }
                                @synchronized(NSStringFromSelector(_cmd)) {
                                    downloadCount--;
                                    if (downloadCount == 0) {
                                        [[YWBuildingManager shareManager] savebuildingJsonWithArray:allBuildings];
                                        [[YWEquipmentManager shareManager] saveEquipmentsWithArray:allEquipments];
                                        [[YWEquipmentManager shareManager] saveEquipmentRulesWithArray:allRules];
                                        if (complete) {
                                            complete(error);
                                        }
                                    }
                                }
                            }];
                            
                        }else{
                            downloadCount--;
                            if (downloadCount == 0) {
                                if (complete) {
                                    complete(error);
                                }
                            }
                        }
                    }else {
                        downloadCount--;
                        if (downloadCount == 0) {
                            if (complete) {
                                complete(error);
                            }
                        }
                    }
                    //规则,只下载一次，因为每个楼盘的规则都是一样的
                    if (idx==0 && (building==nil||building.ruleJsonFileUpdateTime != buildingJsonFile.ruleJsonFileUpdateTime)) {
                        NSString *path = [NSString stringWithFormat:@"%@_ruleZipFile.zip",buildingJsonFile.buildingId];
                        NSString *fullPath = [[YWResourceManager shareManager] fileCachePathFromResourcePath:path];
                        
                        path = [NSString stringWithFormat:@"/ruleUnZipFile_%@",buildingJsonFile.buildingId];
                        NSString *outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];
                        [[YWAliyunOSSManager shareManager] downloadFile:buildingJsonFile.ruleJsonUrl  toFilePath:fullPath progressBlock:nil completeBlock:^(BOOL success) {
                            if (success) {
                                //data为zip 解压
                                NSData *data = [self UnzipFromZipFile:fullPath toPath:outputPath];
                                NSArray* equipmentRules = nil;
                                if (data) {
                                    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                    equipmentRules = [YWEquipmentRulesJson mj_objectArrayWithKeyValuesArray:jsonDict];
                                }
                                
                                if (equipmentRules) {
                                    [allRules addObjectsFromArray:equipmentRules];
                                }
                            }
                            @synchronized(NSStringFromSelector(_cmd)) {
                                downloadCount--;
                                if (downloadCount == 0) {
                                    [[YWBuildingManager shareManager] savebuildingJsonWithArray:allBuildings];
                                    [[YWEquipmentManager shareManager] saveEquipmentsWithArray:allEquipments];
                                    [[YWEquipmentManager shareManager] saveEquipmentRulesWithArray:allRules];
                                    if (complete) {
                                        complete(error);
                                    }
                                }
                            }
                        }];
                    } else {
                        downloadCount--;
                        if (downloadCount == 0) {
                            if (complete) {
                                complete(error);
                            }
                        }
                    }
                }];
            }else{
                if (complete) {
                    complete(error);
                }
            }
        }
        else {
            if (complete) {
                complete(error);
            }
        }
    }];
}

//------这个方法下载数据时，不用限制(例如上面方法中设备的间隔12小时才能下载)
- (void)refreshDownloadBuildingWithComplete:(void (^)(BOOL error))complete{
    [self downloadWithUrl:[YWCommonTool getBuildingJsonUrl] params:nil complete:^(BOOL error, id json) {
        if (!error) {
            if ([json isKindOfClass:[NSArray class]]) {
                NSArray* buildingJsonFiles = [YWBuildingJsonFile mj_objectArrayWithKeyValuesArray:json];
                if (buildingJsonFiles.count == 0) {
                    if (complete) {
                        complete(YES);
                    }
                }
                //每个buildingJsonFiles包含楼盘设备规则3个文件
                __block NSInteger downloadCount = buildingJsonFiles.count * 3;
                __block NSMutableArray* allBuildings = [NSMutableArray array];
                __block NSMutableArray* allEquipments = [NSMutableArray array];
                __block NSMutableArray* allRules = [NSMutableArray array];
                //__block YWLoginUser *currentUser = [YWLoginTool loginUser];
                //楼盘
                [buildingJsonFiles enumerateObjectsUsingBlock:^(YWBuildingJsonFile*  _Nonnull buildingJsonFile, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    NSString *path = [NSString stringWithFormat:@"%@_buildingZipFile.zip",buildingJsonFile.buildingId];
                    NSString *fullPath = [[YWResourceManager shareManager] fileCachePathFromResourcePath:path];
                    path = [NSString stringWithFormat:@"/buildingUnZipFile_%@",buildingJsonFile.buildingId];
                    NSString *outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];
                    [[YWAliyunOSSManager shareManager] downloadFile:buildingJsonFile.buildingJsonUrl toFilePath:fullPath progressBlock:nil completeBlock:^(BOOL success) {
                        if (success) {
                            //data为zip格式数据 解压
                            NSData *data = [self UnzipFromZipFile:fullPath toPath:outputPath];
                            YWBuildingJson* buildingJson = nil;
                            if (data) {
                                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                buildingJson = [YWBuildingJson mj_objectWithKeyValues:jsonDict];
                            }
                            if (buildingJson) {
                                buildingJson.equipmentJsonFileUpdateTime = buildingJsonFile.equipmentJsonFileUpdateTime;
                                buildingJson.buildingJsonFileUpdateTime = buildingJsonFile.buildingJsonFileUpdateTime;
                                buildingJson. ruleJsonFileUpdateTime= buildingJsonFile.ruleJsonFileUpdateTime;
                                [allBuildings addObject:buildingJson];
                            }
                        }
                        @synchronized(NSStringFromSelector(_cmd)) {
                            downloadCount--;
                            if (downloadCount == 0) {
                                [[YWBuildingManager shareManager] savebuildingJsonWithArray:allBuildings];
                                [[YWEquipmentManager shareManager] saveEquipmentsWithArray:allEquipments];
                                [[YWEquipmentManager shareManager] saveEquipmentRulesWithArray:allRules];
                                if (complete) {
                                    complete(error);
                                }
                            }
                        }
                    }];
                    
                    //设备
                    NSString *pathhh = [NSString stringWithFormat:@"%@_equipmentZipFile.zip",buildingJsonFile.buildingId];
                    NSString *fullPathhh = [[YWResourceManager shareManager] fileCachePathFromResourcePath:pathhh];
                    
                    pathhh = [NSString stringWithFormat:@"/equipmentUnZipFile_%@",buildingJsonFile.buildingId];
                    NSString *outputPathhh = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:pathhh];
                    [[YWAliyunOSSManager shareManager] downloadFile:buildingJsonFile.equipmentJsonUrl  toFilePath:fullPathhh progressBlock:nil completeBlock:^(BOOL success) {
                        if (success) {
                            //data为zip 解压
                            NSData *data = [self UnzipFromZipFile:fullPathhh toPath:outputPathhh];
                            NSArray* equipments = nil;
                            if (data) {
                                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                equipments = [YWEquipment mj_objectArrayWithKeyValuesArray:jsonDict];
                            }
                            if (equipments.count>0) {
                                [allEquipments addObjectsFromArray:equipments];
                            }
                        }
                        @synchronized(NSStringFromSelector(_cmd)) {
                            downloadCount--;
                            if (downloadCount == 0) {
                                [[YWBuildingManager shareManager] savebuildingJsonWithArray:allBuildings];
                                [[YWEquipmentManager shareManager] saveEquipmentsWithArray:allEquipments];
                                [[YWEquipmentManager shareManager] saveEquipmentRulesWithArray:allRules];
                                if (complete) {
                                    complete(error);
                                }
                            }
                        }
                    }];
                    
                    //规则,只下载一次，因为每个楼盘的规则都是一样的
                    if (idx==0) {
                        NSString *path = [NSString stringWithFormat:@"%@_ruleZipFile.zip",buildingJsonFile.buildingId];
                        NSString *fullPath = [[YWResourceManager shareManager] fileCachePathFromResourcePath:path];
                        
                        path = [NSString stringWithFormat:@"/ruleUnZipFile_%@",buildingJsonFile.buildingId];
                        NSString *outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];
                        [[YWAliyunOSSManager shareManager] downloadFile:buildingJsonFile.ruleJsonUrl  toFilePath:fullPath progressBlock:nil completeBlock:^(BOOL success) {
                            if (success) {
                                //data为zip 解压
                                NSData *data = [self UnzipFromZipFile:fullPath toPath:outputPath];
                                NSArray* equipmentRules = nil;
                                if (data) {
                                    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                    equipmentRules = [YWEquipmentRulesJson mj_objectArrayWithKeyValuesArray:jsonDict];
                                }
                                
                                if (equipmentRules) {
                                    [allRules addObjectsFromArray:equipmentRules];
                                }
                            }
                            @synchronized(NSStringFromSelector(_cmd)) {
                                downloadCount--;
                                if (downloadCount == 0) {
                                    [[YWBuildingManager shareManager] savebuildingJsonWithArray:allBuildings];
                                    [[YWEquipmentManager shareManager] saveEquipmentsWithArray:allEquipments];
                                    [[YWEquipmentManager shareManager] saveEquipmentRulesWithArray:allRules];
                                    if (complete) {
                                        complete(error);
                                    }
                                }
                            }
                        }];
                    } else {
                        downloadCount--;
                        if (downloadCount == 0) {
                            if (complete) {
                                complete(error);
                            }
                        }
                    }
                }];
            }else{
                if (complete) {
                    complete(error);
                }
            }
        }
        else {
            if (complete) {
                complete(error);
            }
        }
    }];
}

//- (void)downloadMaintenanceTypeWithComplete:(void (^)(BOOL error))complete
//{
//    [self downloadWithUrl:[YWCommonTool getMaintenanceTypeUrl] params:nil complete:^(BOOL error, id json) {
//         if (!error) {
//             NSArray* dictMaintenanceTypes = [YWDictMaintenanceType mj_objectArrayWithKeyValuesArray:json];
//             [[YWEquipmentManager shareManager] saveDictMaintenanceTypesWithArray:dictMaintenanceTypes];
//         }
//        if (complete) {
//            complete(error);
//        }
//    }];
//}


- (void)downloadBuildingMembersWithComplete:(void (^)(BOOL error))complete{
    [self downloadWithUrl:[YWCommonTool getBuildingMembersUrl] params:nil complete:^(BOOL error, id json) {
        if (!error) {
            NSArray *members = [YWProjectMembersJson mj_objectArrayWithKeyValuesArray:json];
            if (members.count>0) {
                [[YWMissionManager shareManager] saveBuildingMembersWithJson:members];
            }
        }
        if (complete) {
            complete(error);
        }
    }];
}

- (void)downloadOrganizationMembersWithComplete:(void (^)(BOOL error))complete{
    [self downloadWithUrl:[YWCommonTool getOrganizationMembersUrl] params:nil complete:^(BOOL error, id json) {
        if (!error) {
            NSArray *handlers = [YWHandler mj_objectArrayWithKeyValuesArray:json];
            if (handlers.count>0) {
                [[YWMissionManager shareManager] saveOrganizationMembersWithArray:handlers];
            }
        }
        if (complete) {
            complete(error);
        }
    }];
}

//- (void)downloadLastMaintenanceTimeWithComplete:(void (^)(BOOL error))complete
//{
//    [self downloadWithUrl:[YWCommonTool getLastMaintenanceTimeUrl] params:nil complete:^(BOOL error, id json) {
//         if (!error) {
//             NSArray* lastMaintenanceTimes = [YWLastMaintenanceTime mj_objectArrayWithKeyValuesArray:json];
//             [[YWEquipmentManager shareManager] saveLastMaintenanceTimeWithArray:lastMaintenanceTimes];
//         }
//        if (complete) {
//            complete(error);
//        }
//    }];
//}

- (void)downloadEwinMenuWithComplete:(void (^)(BOOL error))complete{
    [self downloadWithUrl:[YWCommonTool ewinMenuUrl] params:nil complete:^(BOOL error, id json) {
        if (!error) {
            NSArray* menuArray = [YWEwinMenu mj_objectArrayWithKeyValuesArray:json];
            [[YWEwinManager shareManager] saveEwinMenuWithArray:menuArray];
        }
        if (complete) {
            complete(error);
        }
    }];
}

#pragma mark - 解压zip
- (NSData *)UnzipFromZipFile:(NSString *)zipPath toPath:(NSString *)outPath {
        //    解压
    BOOL successUnzip = [SSZipArchive unzipFileAtPath:zipPath toDestination:outPath];
    if (successUnzip) {
        //    删除解压前文件
        if ([[NSFileManager defaultManager] fileExistsAtPath:zipPath]) {
            [[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil];
        }
        //    获取存放解压文件下的文件名
        NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:outPath error:nil];
        if (directoryContents.count) {
            NSString *unzipPath = [outPath stringByAppendingPathComponent:directoryContents[0]];
            NSData *resultData = [NSData dataWithContentsOfFile:unzipPath];
            
            NSString *receiveStr = [[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
            resultData = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
            //    删除解压后文件
            if ([[NSFileManager defaultManager] fileExistsAtPath:unzipPath]) {
                [[NSFileManager defaultManager] removeItemAtPath:unzipPath error:nil];
            }
            //    删除存放解压文件的文件夹
            if ([[NSFileManager defaultManager] fileExistsAtPath:outPath]) {
                [[NSFileManager defaultManager] removeItemAtPath:outPath error:nil];
            }
            return resultData;
        }else{
            return nil;
        }
    }else {
        return nil;
    }
}

@end
